<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../plugins/layui/css/layui.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/layui/css/style.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../layuiadmin/style/admin.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/zTree/css/metroStyle/metroStyle.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="../plugins/zTree/css/metroStyle/ext.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="//at.alicdn.com/t/c/font_3564966_a6tt4yhnzge.css" media="all">
    <link rel="stylesheet" href="../plugins/toastr/toastr.min.css?v=${.Config.basic.version}">
    <style>

        .layui-form-label {
            float: left;
            display: block;
            padding: 9px 15px;
            width: 60px;
            font-weight: 400;
            line-height: 20px;
            text-align: right;
        }
        .layui-form-label-sm {
            float: left;
            display: block;
            padding: 7px 5px 7px 5px;
            width: 40px;
            font-weight: 400;
            line-height: 20px;
            text-align: right;
        }
        .layui-form-item .layui-input-inline {
            float: left;
            width: 150px;
            margin-right: 10px;
        }
        .layui-form-item {
            margin-top: 5px;
            margin-bottom: 10px;
        }

        .layui-btn + .layui-btn {
            margin-left: 5px;
        }
        .layui-btn-xs {
            height: 18px;
            line-height: 18px;
            padding: 0 5px;
            font-size: 11px;
        }

        .layui-form-label-lg {
            float: left;
            display: block;
            padding: 9px 15px;
            width: 130px;
            font-weight: 400;
            line-height: 20px;
            text-align: right;
        }

        /*.layui-form-item .layui-input[readonly] {*/
        /*    background-color: #0a1434;*/
        /*    color: #a6b8d5;*/
        /*    border: none;*/
        /*    border-top-color: currentcolor;*/
        /*    border-right-color: currentcolor;*/
        /*    border-bottom-color: currentcolor;*/
        /*    border-left-color: currentcolor;*/
        /*}*/
    </style>
    <!-- <style>
        .layui-table-view .layui-table td, .layui-table-view .layui-table th {
            padding: 5px 0;
            border-top: 1px solid #404453;
            border-left: 1px solid #404453;
            border-bottom: 1px solid #404453;
            border-right: 1px solid #404453;
        }
    </style> -->
</head>

<body class="layui-layout-body">
<div class="layui-fluid">
    <div style="display: flex;">
        <div style="width: 250px;">
            <div class="layui-card tree-div">

                <div class="">
                    <div class=" " >
                        <ul id="treeDemo" class="ztree"></ul>
                    </div>
                </div>
            </div>
        </div>

        <div style="width: calc(100% - 250px);float: right; " >
            <div class="left-content layui-card" style="display: none;">
                <div class="layui-card-body">
                    <form class="layui-form" lay-filter="form" id="form" action="">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-sm">栏位</label>
                                <div class="layui-input-inline" style="width: 100px;">
                                    <select name="hnum" lay-verify="" lay-search="">
                                        <option value=""></option>
                                    </select>
                                </div>
                            </div>

                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-sm">SN码</label>
                                <div class="layui-input-inline" style="width: 110px;">
                                    <input type="text" name="sn" lay-verify="" autocomplete="off" class="layui-input">
                                </div>
                            </div>

                            <div class="layui-inline" >
                                <label class="layui-form-label layui-form-label-sm" >日期</label>
                                <div class="layui-input-inline" style="width: 100px;">
                                    <input type="text"  class="layui-input" name="datespan" id="datespan" placeholder=" - ">
                                </div>
                            </div>

                            <!-- <div class="layui-inline" >
                                <label class="layui-form-label layui-form-label-sm" style="width: 60px;">快速同步</label>
                                <div class="layui-input-inline" style="width: 60px;">
                                    <input type="checkbox" name="fastSync" lay-filter="fastSync" style="width: 60px;"  lay-skin="switch" lay-text="|" >
                                </div>
                            </div> -->

                            <div class="layui-inline">
                                <button type="submit" class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="btn_search" lay-filter="btn_search"><i class="layui-icon layui-icon-search"></i>查询</button>
                                <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm action-export layui-hide" lay-submit="btn_export" lay-filter="btn_export"><i class="layui-icon layui-icon-download-circle"></i> 导出</button>
                            </div>

                        </div>
                    </form>

                    <table class="layui-hide" id="table" lay-filter="table"></table>
                    <script type="text/html" id="table_toolbar">
                        <div class="layui-btn-container">
                            <!-- <button class="layui-btn layui-btn-sm layui-btn-normal  action-edit layui-hide" lay-event="addDevice">增加</button> -->
                        </div>
                    </script>

                </div>
            </div>
        </div>
    </div>

</div>

<script src="../plugins/layui/layui.js"></script>
<script src="../plugins/jquery/jquery-3.6.0.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.core.min.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.excheck.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.exedit.js?v=${.Config.basic.version}"></script>
<script src="../plugins/jquery.slimscroll.min.js"></script>
<script src="../plugins/toastr/toastr.min.js"></script>
<script src="../plugins/moment.min.js"></script>
<script src="../js/utils.js"></script>
<script src="../js/verify.js"></script>
<script src="../js/func.js?v=${.Config.basic.version}"></script>
<script>
    var zTree=null;
    var table=null;
    var form=null;
    var Table=null;
    var lay_index=null;
    var laydate = null;
    var fastSync = false;
    var fastSyncAddr = null;
    var fastSyncID = null;

    var token = window.localStorage.getItem("token");
    var user_info=JSON.parse(window.localStorage.getItem("user_info"));
    var func_url="${.func_url}";
    var actions=[];
    var gateways=[];
    var feedNodes=[];
    var token = window.localStorage.getItem("token");
    token = 'Bearer ' + token;
    var selectedTreeNode = null;

    var tree_setting = {
        async: {
            enable: true,
            type: "get",
            headers:{'Authorization':token},
            url: '../Api/Topo/GetAsync',
            autoParam:["id", "type"], //节点参数提交给后台,这里提交id和类型到后台
            otherParam:{"device_type":"DMXFGW"}, //静态参数
            dataFilter: filter,
        },
        view: {
            dblClickExpand: false,
            fontCss: getFont,
            nameIsHTML: true,
        },
        callback: {
            onClick: treeOnClick,
        }
    };
    function filter(treeId, parentNode, res) {
        console.info(res)
        if (!res.data) return null;
        var nodes = res.data;
        nodes=setDataIcon(nodes);
        return nodes;
    }

    layui.config({
        base: '../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index','layer','form', 'table','transfer','laydate'],function(){
        form = layui.form;
        table = layui.table;
        transfer = layui.transfer;
        laydate = layui.laydate;
        var tomorrow = moment().add(1,"days").format('YYYY-MM-DD');
        var today = moment().format('YYYY-MM-DD');
        var yestoday = moment().add(-1,"days").format('YYYY-MM-DD');
        laydate.render({
            elem: '#datespan'
            ,type: 'date'
            //,range: '~'
            , theme: '#3c7cff'
            ,value: today
            ,isInitValue: true
            ,done: function(value, date, endDate){
                //setTimeout(function(){load();},200);
            }
        });

        toastr.options = {
            "closeButton": false, //是否显示关闭按钮
            "debug": false, //是否使用debug模式
            "positionClass": "toast-top-center",//弹出窗的位置
            "showDuration": "300",//显示的动画时间
            "hideDuration": "1000",//消失的动画时间
            "timeOut": "2000", //展现时间
            "extendedTimeOut": "1000",//加长展示时间
            "showEasing": "swing",//显示时的动画缓冲方式
            "hideEasing": "linear",//消失时的动画缓冲方式
            "showMethod": "fadeIn",//显示时的动画方式
            "hideMethod": "fadeOut" //消失时的动画方式
        };

        form.verify({
            verify_ip:verify_ip,
            addr: function(value, item){ //value：表单的值、item：表单的DOM对象
                if(/^\d+\d+\d$/.test(value)==false){
                    return '必须是10进制数值';
                }
                if(value.length!==10){
                    return '长度必须是10';
                }
            },
            percent: function(value, item){ //value：表单的值、item：表单的DOM对象
                if(/^([0-9]{1,2}|100)$/.test(value)==false){
                    return '0-100之间的正整数';
                }
            },
        });


        $.ajax({
            type: 'GET',
            url: '../Api/User/Actions',
            data: {func_url:func_url},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                console.info(data)
                actions=data.data;
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });

        /*form.on('switch(fastSync)', function(data){
             //开关是否开启，true或者false
            fastSync = data.elem.checked?true:false;
            console.log("fastSync",fastSync);
            console.log("fastSyncAddr",fastSyncAddr);
            if(fastSyncID){
                clearInterval(fastSyncID);
            }
            if(fastSync){
                fastSyncID = setInterval(function(){
                    getStatus(fastSyncAddr).then(function(res){
                        if(res.code>=0){
                        }
                    });
                },5*1000);
            }
            
        });*/


        //监听提交
        form.on('submit(btn_search)', function(data){

            //var obj={};

            /*var date = data.field.datespan.split(" ~ ");
            if(date.length==2){
                data.field.begin=date[0];
                data.field.end=date[1];
            }else{
                data.field.begin='';
                data.field.end='';
            }*/

            data.field.begin = data.field.datespan;
            data.field.end = moment(data.field.begin).add(1,"days").format('YYYY-MM-DD')

            if(selectedTreeNode.type=="house"){
                data.field.houseid = selectedTreeNode.id;
            }else if(selectedTreeNode.type=="farm"){
                data.field.farmid = selectedTreeNode.id;
            }else if(selectedTreeNode.type=="hnum"){
                data.field.hnum_prefix = selectedTreeNode.hnum_prefix;
                data.field.houseid = selectedTreeNode.houseid;
            }
            search(data.field);
            console.info(data.field);
            return false;
        });

        form.on('submit(btn_export)', function(data){
            //toastr.warning("待开发");
            
            /*var date = data.field.datespan.split(" ~ ");
            if(date.length==2){
                data.field.begin=date[0];
                data.field.end=date[1];
            }else{
                data.field.begin='';
                data.field.end='';
            }*/
            data.field.begin = data.field.datespan;
            data.field.end = moment(data.field.begin).add(1,"days").format('YYYY-MM-DD')

            if(selectedTreeNode.type=="house"){
                data.field.houseid = selectedTreeNode.id;
            }else if(selectedTreeNode.type=="farm"){
                data.field.farmid = selectedTreeNode.id;
            }else if(selectedTreeNode.type=="hnum"){
                data.field.hnum_prefix = selectedTreeNode.hnum_prefix;
                data.field.houseid = selectedTreeNode.houseid;
            }

            //data.field.begin_end=0;
            console.info(data.field);
            //return false;
            layer.load(1);
            var url="../Api/History/FeedRecord/Export?"+encodeUrl(data.field);
            console.info(url);

            var xhh = new XMLHttpRequest();
            xhh.open("get", url );
            xhh.setRequestHeader("Authorization", token);
            xhh.setRequestHeader("Content-Type","application/json");
            xhh.responseType = 'blob';
            xhh.onload = function () {
                layer.closeAll('loading');
                // 请求完成
                if (this.status === 200) {
                    // 返回200
                    var blob = this.response;
                    var reader = new FileReader();
                    reader.readAsDataURL(blob);    // 转换为base64，可以直接放入a表情href
                    reader.onload = function (e) {
                        // 转换完成，创建一个a标签用于下载
                        var a = document.createElement('a');
                        a.download = "饲喂记录.xlsx";
                        a.href = e.target.result;
                        $("body").append(a);    // 修复firefox中无法触发click
                        a.click();
                        $(a).remove();
                    }
                }else{
                    console.debug(this);
                }
            };
            xhh.send();

            return false;
        });

        //头工具栏事件
        table.on('toolbar(table)', function(obj){
            switch(obj.event){
                case 'addDevice':
                    onAdd();
                    break;

            };
        });

        //监听行工具事件
        table.on('tool(table)', function(obj){
            var data = obj.data;
            if(data.remark){

            }else{
                data.remark="";
            }
            console.log(obj)
            if(obj.event === 'delete'){
                onDelete(data);
            }
            else if(obj.event === 'edit'){
                onEdit(data);
            }
            else if(obj.event === 'update'){
                onUpdate(data);
            }
            else if(obj.event === 'updateNode'){
                onUpdateNode(data);
            }
            else if(obj.event === 'param'){
                onParam(data);
            }
            else if(obj.event === 'status'){
                onStatus(data);
            }
            else if(obj.event === 'allocate'){
                onAllocate(data);
            }
        });

        table.on('sort(table)', function(obj){

            table.reload('table', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    //order_field: obj.field //排序字段
                    //,order_type: obj.type //排序方式
                    order:obj.field+" "+(obj.type||"")
                }
            });
        });




        //加载tree
        loadTree();
        resizeElement();
    });

    function encodeUrl(obj) {
        var str = [];
        for (var p in obj)
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    }

    function getFont(treeId, node) {
        return node.font ? node.font : {};
    }

    function treeOnClick(event, treeId, treeNode) {
        selectedTreeNode=treeNode;
        resizeElement();
        console.info(selectedTreeNode);
        if(selectedTreeNode.type=="root"){
            $(".left-content").hide();
            toastr.info("请选择栏舍单元");
            //on_view_root();
        } else if(selectedTreeNode.type=="farm"){
            // $(".left-content").children("div").hide();
            // $(".device_block").show();
            // $("#id-title").html(selectedTreeNode.name);
            // renderSelect(selectedTreeNode.id);
            // initTable();
            $(".left-content").hide();
            toastr.info("请选择栏舍单元");

        }else if(selectedTreeNode.type=="house"){
            $(".left-content").show();
            $("#id-title").html(selectedTreeNode.name);
            renderSelect(selectedTreeNode.id);
            initTable();
        }else if(selectedTreeNode.type=="hnum"){
            $(".left-content").show();
            $("#id-title").html(selectedTreeNode.name);
            renderSelect();
            initTable();
        } else{
            $(".left-content").hide();
            $(".bg").show();
        }

    }

    function treeOnExpand(event, treeId, treeNode) {
    }

    function treeOnCollapse(event, treeId, treeNode) {
        console.info(treeNode);
    }
    function deepCopy(obj) {
        if (typeof obj != 'object') {
            return obj;
        }
        var newobj = {};
        for (var attr in obj) {
            newobj[attr] = deepCopy(obj[attr]);
        }
        return newobj;
    }

    function renderSelect(){
        var obj={};
        if(selectedTreeNode.type=="house"){
            obj={houseid:selectedTreeNode.id};
        }else if(selectedTreeNode.type=="farm"){
            obj={farmid:selectedTreeNode.id};
        }else if(selectedTreeNode.type=="hnum"){
            obj={houseid:selectedTreeNode.houseid,hnum_prefix:selectedTreeNode.hnum_prefix};
        }
        $.ajax({
            type: 'GET',
            url: '../Api/Utils/Hnum',
            data: obj,
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res)
                if(res.code>=0){
                    var items = res.data;
                    console.info(items)
                    //栏舍下拉
                    var html="<option value='' ></option>";
                    for(var i=0;i<items.length;i++){
                        var selectd="";
                        html+="<option "+selectd+" value=\""+items[i].hnum+"\">"+items[i].hnum+"</option>";
                    }
                    $("select[name='hnum']").html(html);
                    form.render('select');
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载设备类型失败');
            }
        });

    }

    function getSimpleNodes(){ 
        loadSimpleNodes().then(function(res){
            if(res.code>=0){
                console.info(res.data);
                feedNodes = res.data;
                initTable();
            }
        });
    }

    function loadSimpleNodes(){
        //promise写法
        var promise = new Promise(function(resolve, reject) {
            var obj=form.val("form");
            console.info(obj);
            if(selectedTreeNode.type=="house"){
                obj.houseid = selectedTreeNode.id;
            }else if(selectedTreeNode.type=="farm"){
                obj.farmid = selectedTreeNode.id;
            }else if(selectedTreeNode.type=="hnum"){
                obj.hnum_prefix = selectedTreeNode.hnum_prefix;
                obj.houseid = selectedTreeNode.houseid;
            }
            $.ajax({
                type: 'GET',
                url: '../Api/Device/Feednode/Simple',
                data: obj,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    
    function initTable(){
        var obj=form.val("form");
        console.info(obj);
        if(selectedTreeNode.type=="house"){
            obj.houseid = selectedTreeNode.id;
        }else if(selectedTreeNode.type=="farm"){
            obj.farmid = selectedTreeNode.id;
        }else if(selectedTreeNode.type=="hnum"){
            obj.hnum_prefix = selectedTreeNode.hnum_prefix;
            obj.houseid = selectedTreeNode.houseid;
        }
        var date = obj.datespan.split(" ~ ");
        if(date.length==2){
            obj.begin=date[0];
            obj.end=date[1];
        }else{
            obj.begin='';
            obj.end='';
        }

        obj.begin = obj.datespan;
        obj.end = moment(obj.begin).add(1,"days").format('YYYY-MM-DD')
        //obj.begin_end=0;
        obj.order = "rectime desc,rid DESC";

        Table = table.render({
            elem: '#table'

            ,url: "../Api/History/FeedRecord/Page"
            ,height: 'full-80'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: obj
            ,page: {
                limit:300,
                limits:[10, 20, 30, 40, 50,100,200,300,400],
                theme: '#3c7cff'
            }
            /*,initSort: {
                field: 'hnum' //排序字段，对应 cols 设定的各字段名
                ,type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
            }*/
            ,limit:30
            ,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports']
            ,title: ''
            ,even:true
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: [[
                //{type: 'checkbox', fixed: 'left'}
                //
                {field:'',title:'序号',type:'numbers'},
                {field:'rid', title:'记录ID',width:100, sort: true}
                ,{field:'addr', title:'网关SN',width:100, sort: true}
                ,{field:'sn', title:'SN',width:110, sort: true,templet: function(d) {   
                    //补全SN到8位，前面补0
                    var sn = parseInt(d.sn);
                    sn = sn.toString().padStart(8, '0');
                    return sn;
                }}
                ,{field:'hnum', title:'栏位号',width:90, sort: true}
                ,{field:'', title:'设备',width:80, sort: false, templet: function(d) {
                    var sn = parseInt(d.sn);
                    //查找feedNodes中匹配sn的item
                    /*var item = feedNodes.find(function(item){
                        return item.sn==sn;
                    });
                    if(item && item.model=="feed"){
                        return "饲喂器";
                    }
                    else if(item && item.model=="fg"){
                        return "粥料器";
                    }
                    else{
                        return "未知";
                    }*/
                   //

                   if(sn<20000000){
                        return "饲喂器";
                   }else{
                        return "粥料器";
                   }
                }}
                ,{field:'rectime', title:'记录时间',width:150, sort: true,templet: function(d){
                        var html = "";
                        html = moment(d.rectime).format("YYYY-MM-DD HH:mm:ss");
                        return html;
                    }}

                ,{field:'mode', title:'模式',width:70, sort: false,align:'center',templet: function(d){
                        var html = "";
                        var sn = parseInt(d.sn);
                        if(sn<20000000){
                            html = decodeModeNew(d.mode);
                        }else{
                            html = decodeFgMode(d.mode);
                        }
                        
                        return html;
                    }}
                /*,{field:'remote', title:'远程',width:70, sort: false,align:'center',templet: function(d){
                        return d.remote?"<i class=\"layui-icon layui-icon-circle-dot layui-text-green \" ></i>":"";
                    }}*/
                ,{field:'auto', title:'方式',width:80, sort: false,align:'center',templet: function(d){
                        if(d.tb_record){
                            return "";
                        }else{
                            var desc="";
                            if(d.auto){
                                desc = "自动";
                            }else{
                                desc = "手动";
                            }
                            if(d.remote){
                                desc+="(远程)";
                            }
                            if(d.emergency){
                                desc+="(紧急)";
                            }
                            return d.auto?"<span class=\"layui-text-green \" >"+desc+"</span>":"<span class=\"layui-text-orange\">"+desc+"</span>";
                        }  
                    }}
                ,{field:'feed_type', title:'类型',width:70, sort: false,align:'center',templet: function(d){
                        if(d.tb_record){
                            return "";
                        }else{
                            return d.feed_type?"<span class=\"layui-text-orange-light \" >出料</span>":"<span class=\"layui-text-blue-light\">出水</span>";
                        }
                    }}
                ,{field:'begin_end', title:'开始/结束',width:90, sort: false,align:'center',templet: function(d){
                        if(d.tb_record){
                            return "";
                        }else{
                            return d.begin_end?"<span  >开始</span>":"<span>结束</span>";
                        }
                        
                    }}
                ,{field:'err', title:'告警',width:80, sort: false,align:'center',templet: function(d){
                        return d.err>0?"<i class=\"layui-icon layui-icon-circle-dot layui-text-red \" ></i>":"";
                    }}
                ,{field:'max_feed', title:'当天最大出料',width:110, sort: false,align:'right',templet: function(d){
                    return d.tb_record?"":d.max_feed+"kg";
                }}
                ,{field:'amount', title:'出料水',width:100, sort: false,align:'right',templet: function(d){
                        if(d.begin_end==0 && d.feed_type==1 && d.amount==0){
                            return "<span class='layui-text-red'>"+ d.amount + "kg (空转)</span>";
                        }else{
                            return d.tb_record?"":d.amount + (d.feed_type?"kg":"L");
                        }
                    }}
                ,{field:'day_use_feed', title:'累计出料',width:100, sort: false,align:'right',templet: function(d){
                        return d.tb_record?"":d.day_use_feed+"kg"+(d.auto>0?"(自)":"(手)");
                    }}
                ,{field:'day_use_water', title:'累计出水',width:100, sort: false,align:'right',templet: function(d){
                        return d.tb_record?"":d.day_use_water+"L"+(d.auto>0?"(自)":"(手)");
                    }}
                ,{field:'food_left', title:'有余料',width:80, sort: false,align:'center',templet: function(d){
                        return d.food_left?"<i class=\"layui-icon layui-icon-circle-dot layui-text-green \" ></i>":"";
                    }}
                ,{field:'tb', title:'有无触碰杆',width:90, sort: false,align:'center',templet: function(d){
                        return d.tb?"<i class=\"layui-icon layui-icon-circle-dot layui-text-green \" ></i>":"";
                    }}
                ,{field:'tb_record', title:'触碰动作',width:80, sort: false,align:'center',templet: function(d){
                        return d.tb_record?"<i class=\"layui-icon layui-icon-circle-dot layui-text-green \" ></i>":"";
                    }}
                ,{field:'debug', title:'调试值',width:100, sort: false,align:'left'}

                ,{field:'', title:'刺激下料是否下水',width:150, sort: false,align:'center',templet: function(d){
                    var html="";
                    if(d.flag_mode_bits){
                        var bit_arr = d.flag_mode_bits.split(",");
                        if(bit_arr[0]>0){
                            html = "<i class=\"layui-icon layui-icon-circle-dot layui-text-green \" ></i>";
                        }
                    }
                    return html;
                }}
                ,{field:'', title:'时间段内未主动有效触碰退出',width:180, sort: false,align:'center',templet: function(d){
                    var html="";
                    if(d.flag_mode_bits){
                        var bit_arr = d.flag_mode_bits.split(",");
                        if(bit_arr[1]>0){
                            html = "<i class=\"layui-icon layui-icon-circle-dot layui-text-green \" ></i>";
                        }
                    }
                    return html;
                }}
                ,{field:'', title:'15分钟未触碰退出',width:150, sort: false,align:'center',templet: function(d){
                    var html="";
                    if(d.flag_mode_bits){
                        var bit_arr = d.flag_mode_bits.split(",");
                        if(bit_arr[2]>0){
                            html = "<i class=\"layui-icon layui-icon-circle-dot layui-text-green \" ></i>";
                        }
                    }
                    return html;
                }}
                ,{field:'', title:'智能未触碰退出',width:150, sort: false,align:'center',templet: function(d){
                    var html="";
                    if(d.flag_mode_bits){
                        var bit_arr = d.flag_mode_bits.split(",");
                        if(bit_arr[3]>0){
                            html = "<i class=\"layui-icon layui-icon-circle-dot layui-text-green \" ></i>";
                        }
                    }
                    return html;
                }}
                ,{field:'', title:'吃完退出',width:80, sort: false,align:'center',templet: function(d){
                    var html="";
                    if(d.flag_mode_bits){
                        var bit_arr = d.flag_mode_bits.split(",");
                        if(bit_arr[4]>0){
                            html = "<i class=\"layui-icon layui-icon-circle-dot layui-text-green \" ></i>";
                        }
                    }
                    return html;
                }}

                //,{field:'event', title:'描述',width:110, sort: false,align:'left'}
                ,{field:'cnt_gap_time', title:'保护时间',width:100, sort: false,align:'left'}
                ,{field:'step_mr', title:'状态标志',width:100, sort: false,align:'left'}
                
                
                ,{field:'vin_calc', title:'输入电压',width:90, sort: false,align:'right'}
                ,{field:'motor_vol', title:'电机电压',width:90, sort: false,align:'right'}
                ,{field:'motor_cur', title:'电机电流',width:90, sort: false,align:'right',templet: function(d){
                        return d.tb_record?"":d.motor_cur;
                    }}

            ]]
            ,done: function(res, curr, count){
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
                // var that = this.elem.next();
                // res.data.forEach(function (item, index) {
                //     //console.log(item.empName);item表示每列显示的数据
                //     if (index % 2 != 0) {
                //         var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", "#0a1434");
                //     } else {
                //         var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", "#00092b");
                //     }
                // });
                var items = res.data;
                if(items&&items.length>0){
                    fastSyncAddr = items[0].addr;
                }
            }
        });
    }



    function search(params) {
        Table.reload({
            where: params
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    }

    function loadTree() {
        //layer.load(1);
        /*$.ajax({
            type: 'GET',
            url: '../Api/Topo',
            data: {show_hnum:0},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                //var data=data.data;
                var nodes=setDataIcon(data.data);
                console.info(nodes);
                zTree = $.fn.zTree.init($("#treeDemo"), tree_setting, nodes);

                var nodes = zTree.getNodesByParam("type", "farm", null);
                if(nodes.length>0){
                    const node = nodes[0];
                    console.info(node);
                    zTree.selectNode(node);
                    setTimeout(function(){zTree.setting.callback.onClick(null,null,node);},200);


                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },
        });
        */
        zTree = $.fn.zTree.init($("#treeDemo"), tree_setting);
    }

    function getStatus(addr){
        //console.info(item);
        var url = '../Api/Device/Gw/Status';
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'GET',
                url: url,
                data: {addr:addr},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //设置图标
    function setDataIcon(data){

        for(let i=0; i<data.length; i++){
            var node=data[i];

            node['font']={'color':'#333'};
            if(node.type=='group'){
                //node.name = "";
                node["icon"]="../plugins/zTree/css/metroStyle/img/net.png";
                //node.isParent=true;
                node.open = true;
            }
            else if(node.type=='area'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/area.png";
                //node.isParent=true;
                node.open = true;
            }
            else if(node.type=='farm'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/location.png";
                node.isParent=true;
            }else if(node.type=='house'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/house.png";
                node.isParent=false;
                if(node.device_online)
                {
                    node['font']={'color':'#3c7cff'};
                }else{
                    node['font']={'color':'#A3A8B6'};
                }
                //node['font']={'color':'#4958b9','font-weight':"bold"};
            }
            else if(node.type=='hnum') {
                node["icon"] = "../plugins/zTree/css/metroStyle/img/farm.png";
                //node.isParent=true;
                //node.open=true;
            }
            if(node['children']){
                var data1=node.children;
                setDataIcon(data1);
            }
        }
        return data;
    }

    $(window).resize(function () {
        //console.info('resize')
        resizeElement();
    });
    function resizeElement() {
        //$('.tree-div').height($(window).height()-60);
        $(".tree-div").slimScroll({
            height: $(window).height()-10,
            size: '4px', //组件宽度
            color: '#eee', //滚动条颜色
            position: 'right', //组件位置：left/right
            distance: '0px', //组件与侧边之间的距离
            start: 'top', //默认滚动位置：top/bottom
            opacity: .4, //滚动条透明度
            alwaysVisible: true, //是否 始终显示组件
            disableFadeOut: false, //是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
            railVisible: true, //是否 显示轨道
            railColor: '#333', //轨道颜色
            railOpacity: .2, //轨道透明度
            railDraggable: true, //是否 滚动条可拖动
            railClass: 'slimScrollRail', //轨道div类名
            barClass: 'slimScrollBar', //滚动条div类名
            wrapperClass: 'slimScrollDiv', //外包div类名
            allowPageScroll: true, //是否 使用滚轮到达顶端/底端时，滚动窗口
            wheelStep: 10, //滚轮滚动量
            touchScrollStep: 200, //滚动量当用户使用手势
            borderRadius: '7px', //滚动条圆角
            railBorderRadius: '7px' //轨道圆角
        });
    }

</script>
<script src="../js/check_screen.js?v=${.Config.basic.version}"></script>

</body>


</html>